<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>绘制一个点</title>
  </head>
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <script>
      // 1. 获取Canvas元素和WebGL上下文
      const canvas = document.getElementById('canvas')
      let gl = canvas.getContext('webgl')

      if (!gl) {
        alert('WebGL not supported, falling back on experimental-webgl')
        gl = canvas.getContext('experimental-webgl')
      }

      if (!gl) {
        alert('Your browser does not support WebGL')
      }

      // 2. 编写顶点着色器和片段着色器的源码
      const vsSource = `
      void main() {
        gl_Position = vec4(0.0, 0.0, 0.0, 1.0); // 设置点的位置
        gl_PointSize = 10.0; // 设置点的大小
      }
      `

      const fsSource = `
      void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // 设置点的颜色为红色
      }
      `

      // initShader函数实现
      function initShader(gl, vsSource, fsSource) {
        function compileShader(type, source) {
          const shader = gl.createShader(type)
          gl.shaderSource(shader, source)
          gl.compileShader(shader)
          if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            console.error('An error occurred compiling the shaders:', gl.getShaderInfoLog(shader))
            gl.deleteShader(shader)
            return null
          }
          return shader
        }

        const vertexShader = compileShader(gl.VERTEX_SHADER, vsSource)
        const fragmentShader = compileShader(gl.FRAGMENT_SHADER, fsSource)
        const shaderProgram = gl.createProgram()
        gl.attachShader(shaderProgram, vertexShader)
        gl.attachShader(shaderProgram, fragmentShader)
        gl.linkProgram(shaderProgram)

        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
          console.error('Unable to initialize the shader program:', gl.getProgramInfoLog(shaderProgram))
          return null
        }

        return shaderProgram
      }

      const program = initShader(gl, vsSource, fsSource)

      // 5. 使用着色器程序
      gl.useProgram(program)

      // 6. 绘制一个点
      gl.drawArrays(gl.POINTS, 0, 1) // 使用gl.POINTS模式绘制一个点
    </script>
  </body>
</html>
